const express = require('express');
const sqlite3 = require('sqlite3').verbose();
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
const multer = require('multer');
const path = require('path');
const fs = require('fs');
const dotenv = require('dotenv');

dotenv.config();

const app = express();
const upload = multer({ dest: 'uploads/' });
const db = new sqlite3.Database('users.db');
const SECRET_KEY = process.env.JWT_SECRET_KEY;

if (!SECRET_KEY) {
    console.error('JWT_SECRET_KEY is not set in the environment variables');
    process.exit(1);
}

app.use(express.json());

// 创建用户表
db.serialize(() => {
    db.run(`CREATE TABLE IF NOT EXISTS users (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        username TEXT UNIQUE,
        password TEXT,
        root_path TEXT
    )`);

    // 添加测试用户
    db.get("SELECT * FROM users WHERE username = 'zs'", (err, row) => {
        if (err) {
            console.error(err);
            return;
        }
        if (!row) {
            bcrypt.hash('ddd', 10, (err, hash) => {
                if (err) throw err;
                db.run("INSERT INTO users (username, password, root_path) VALUES (?, ?, ?)", ['zs', hash, '/home/zs']);
                db.run("INSERT INTO users (username, password, root_path) VALUES (?, ?, ?)", ['ls', hash, '/home/ls']);
            });
        }
    });
});

// 中间件：验证 token
function authenticateToken(req, res, next) {
    const authHeader = req.headers['authorization'];
    const token = authHeader && authHeader.split(' ')[1];

    if (token == null) return res.sendStatus(401);

    jwt.verify(token, SECRET_KEY, (err, user) => {
        if (err) return res.sendStatus(403);
        req.user = user;
        next();
    });
}

// 登录路由
app.post('/login', (req, res) => {
    const { username, password } = req.body;
    db.get("SELECT * FROM users WHERE username = ?", [username], (err, user) => {
        if (err) return res.status(500).json({ message: "服务器错误" });
        if (!user) return res.status(400).json({ message: "用户不存在" });

        bcrypt.compare(password, user.password, (err, result) => {
            if (err) return res.status(500).json({ message: "服务器错误" });
            if (!result) return res.status(400).json({ message: "密码错误" });

            const token = jwt.sign({ username: user.username, root_path: user.root_path }, SECRET_KEY, { expiresIn: '1h' });
            res.json({ token });
        });
    });
});

// 上传文件
app.post('/upload', authenticateToken, upload.single('file'), (req, res) => {
    if (!req.file) {
        return res.status(400).json({ message: "没有文件上传" });
    }

    const filePath = path.join(req.user.root_path, req.query.path || '', req.file.originalname);
    fs.rename(req.file.path, filePath, (err) => {
        if (err) {
            return res.status(500).json({ message: "文件上传失败" });
        }
        res.json({ message: "文件上传成功" });
    });
});

// 下载文件
app.get('/download', authenticateToken, (req, res) => {
    const filePath = path.join(req.user.root_path, req.query.path || '', req.query.file);
    if (fs.existsSync(filePath) && fs.statSync(filePath).isFile()) {
        res.download(filePath);
    } else {
        res.status(404).json({ message: "文件不存在" });
    }
});

// 删除文件或目录
app.delete('/delete', authenticateToken, (req, res) => {
    const targetPath = path.join(req.user.root_path, req.body.path || '', req.body.name);
    if (fs.existsSync(targetPath)) {
        if (fs.statSync(targetPath).isDirectory()) {
            fs.rmdirSync(targetPath, { recursive: true });
        } else {
            fs.unlinkSync(targetPath);
        }
        res.json({ message: "删除成功" });
    } else {
        res.status(404).json({ message: "文件或目录不存在" });
    }
});

// 重命名文件或目录
app.put('/rename', authenticateToken, (req, res) => {
    const oldPath = path.join(req.user.root_path, req.body.path || '', req.body.oldName);
    const newPath = path.join(req.user.root_path, req.body.path || '', req.body.newName);
    if (fs.existsSync(oldPath)) {
        fs.renameSync(oldPath, newPath);
        res.json({ message: "重命名成功" });
    } else {
        res.status(404).json({ message: "文件或目录不存在" });
    }
});

// 创建目录
app.post('/mkdir', authenticateToken, (req, res) => {
    const dirPath = path.join(req.user.root_path, req.body.path || '', req.body.name);
    if (!fs.existsSync(dirPath)) {
        fs.mkdirSync(dirPath, { recursive: true });
        res.json({ message: "目录创建成功" });
    } else {
        res.status(400).json({ message: "目录已存在" });
    }
});

// 列出目录内容
app.get('/list', authenticateToken, (req, res) => {
    const dirPath = path.join(req.user.root_path, req.query.path || '');
    if (fs.existsSync(dirPath) && fs.statSync(dirPath).isDirectory()) {
        const items = fs.readdirSync(dirPath).map(item => {
            const itemPath = path.join(dirPath, item);
            return {
                name: item,
                isDir: fs.statSync(itemPath).isDirectory()
            };
        });
        res.json({ items });
    } else {
        res.status(404).json({ message: "目录不存在" });
    }
});

// 切换目录
app.post('/cd', authenticateToken, (req, res) => {
    const targetPath = path.join(req.user.root_path, req.body.path);
    if (fs.existsSync(targetPath) && fs.statSync(targetPath).isDirectory()) {
        res.json({ message: "目录切换成功" });
    } else {
        res.status(404).json({ message: "目录不存在" });
    }
});

const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
    console.log(`服务器运行在 http://localhost:${PORT}`);
});
